package com.mMap.controller;

import com.mMap.service.UserInfoService;
import com.mMap.entity.dto.SessionWebUserDto;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mMap.annotation.GlobalInterceptor;
import com.mMap.annotation.VerifyParam;
import com.mMap.entity.vo.ResponseVO;
import com.mMap.entity.constants.Constants;
import com.mMap.entity.enums.VerifyRegexEnum;
import com.mMap.exception.BusinessException;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
@RestController
public class AccountController extends ABaseController{
    @Resource
    private UserInfoService userInfoService;

    @RequestMapping("/reqister")
    @GlobalInterceptor(checkParams= true,checkLogin = false)
    public ResponseVO register(HttpSession session,
                               @VerifyParam(required = true, regex = VerifyRegexEnum.EMAIL,max = 150) String email,
                               @VerifyParam(required = true) String nickName,
                               @VerifyParam(required = true, regex = VerifyRegexEnum.PASSWORD, min = 8, max = 18) String password,
                               @VerifyParam(required = true) String role,
                               @VerifyParam(required = true) String phone
    ) {
        try {
            String msg= userInfoService.register(email, nickName, password, phone,role);
            return getSuccessResponseVO(null,msg);
        } finally {
            session.removeAttribute(Constants.CHECK_CODE_KEY);
        }
    }
    @RequestMapping("/login")
    @GlobalInterceptor(checkParams= true, checkLogin = false)
    public ResponseVO login(HttpSession session,
                               @VerifyParam(required = true) String email,
                               @VerifyParam(required = true) String password
    ) {
        try {
//            if (!checkcode.egualsgnoreCase((string) session.getAttribute(Constants.CHECK_CODE_KEY))) {
//                throw new BusinessException("图片验证码不正确");
//            }

            SessionWebUserDto sessionWebUserDto = userInfoService.login(email, password);
            session.setAttribute(Constants.SESSION_KEY, sessionWebUserDto);
            session.setMaxInactiveInterval(Constants.REDIS_KEY_EXPIRES_DAY);
            System.out.println("session.getId()");
            System.out.println(session.getId());
            System.out.println("User logged in successfully. SessionWebUserDto: " + sessionWebUserDto);
            return getSuccessResponseVO(sessionWebUserDto);
        } finally {
            session.removeAttribute(Constants.CHECK_CODE_KEY);
        }
    }

    @RequestMapping("/logout")
    public ResponseVO logout(HttpSession session) {
        session.invalidate();
        return getSuccessResponseVO(null);
    }
}

